# -*- coding: UTF-8 -*-
"""
@Project :xlx-fastapi
@File    :admin_identity_token_dao.py
@Author  :xlx-ali
@Date    :2024/06/24 14:43 星期一
"""
from sqlalchemy import select, update, delete

from app.dao.models import t_xlx_admin_identity_token
from app.types import apiproto
from .base_dao import getDatabaseSession


class AdminIdentityTokenQueryDao(object):
    """TOKEN查询类dao"""

    @classmethod
    def findByAdminId(cls, admin_id: int) -> apiproto.AdminIdentityTokenDetailProto:
        """单条查询示例"""
        with getDatabaseSession() as session:
            s = select([t_xlx_admin_identity_token]).where(t_xlx_admin_identity_token.c.admin_id == admin_id)
            result = session.execute(s).first()
        return result


class AdminIdentityTokenOperateDao(object):
    """操作TOKEN相关dao"""

    @classmethod
    def insertGetId(cls, data: apiproto.AdminIdentityTokenDetailProto) -> int:
        with getDatabaseSession() as session:
            insert_stmt = t_xlx_admin_identity_token.insert().values(admin_id=data.admin_id, token=data.token,
                                                                     updatetime=data.updatetime, expire=data.expire)
            session.execute(insert_stmt)
            return data.admin_id

    @classmethod
    def updateByAdminId(cls, admin_id: int, **kwargs):
        with getDatabaseSession() as session:
            update_stmt = update(t_xlx_admin_identity_token)
            update_stmt = update_stmt.where(t_xlx_admin_identity_token.c.admin_id == admin_id)
            for column, value in kwargs.items():
                if hasattr(t_xlx_admin_identity_token.c, column):
                    update_stmt = update_stmt.values({column: value})
                else:
                    raise ValueError(f"Invalid column name: {column}")
            result = session.execute(update_stmt)
            return result.rowcount

    @classmethod
    def delByAdminId(cls, admin_id: int):
        with getDatabaseSession() as session:
            delete_stmt = delete(t_xlx_admin_identity_token)
            delete_stmt = delete_stmt.where(t_xlx_admin_identity_token.c.admin_id == admin_id)
            result = session.execute(delete_stmt)
            return result.rowcount

    # @classmethod
    # def updataAdmin(cls, user: XlxAdmin) -> XlxAdmin:
    #     """更新数据"""
    #     with getDatabaseSession() as session:
    #         query = session.query(XlxAdmin).filter(XlxAdmin.id == user.id).first()
    #         query.last_login_time = user.last_login_time
    #         query.last_login_ip = user.last_login_ip,
    #         query.last_login_ipaddress = user.last_login_ipaddress
    #         session.commit()
    #         session.refresh(query)

    #     return query
